import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import dataEditCreate from '../../addons/DataEdit'
import * as datetime from '../../../utils/datetime'
import dataTableCreate from '../../addons/DataTable'
import * as otherService from '../../../services/other';
const daoName = "LSJJDTDRTJ";
const ButtonGroup = Button.Group;
const columns = [
  { title: '数据日期', width: 120, sorter: true, dataIndex: 'DTID', key: 'DTID', dispaly: true, filter: true, export: false },
  { title: '定投编号', width: 180, sorter: true, dataIndex: 'DTBH', key: 'DTBH', dispaly: true, filter: true, export: true },
  { title: '银行账号', width: 120, sorter: true, dataIndex: 'YHZH', key: 'YHZH', dispaly: true, filter: true, export: true },
  { title: '客户名称', width: 200, sorter: true, dataIndex: 'KHMC', key: 'KHMC', dispaly: true, filter: true, export: true },
  { title: '证件号码', width: 200, sorter: true, dataIndex: 'ZJHM', key: 'ZJHM', dispaly: true, filter: true, export: true },
  { title: 'TA名称', width: 120, sorter: true, dataIndex: 'TAMC', key: 'TAMC', dispaly: true, filter: true, export: true },
  { title: '产品代码', width: 120, sorter: true, dataIndex: 'CPDM', key: 'CPDM', dispaly: true, filter: true, export: true },
  { title: '产品名称', width: 200, sorter: true, dataIndex: 'CPMC', key: 'CPMC', dispaly: true, filter: true, export: true },
  { title: '投资金额', width: 120, sorter: true, key: 'TZJE', dataIndex: "TZJE", dispaly: true, canEdit: true, export:true },
  { title: '投资日', width: 120, sorter: true, key: 'TZR', dataIndex: "TZR", dispaly: true, canEdit: true, export:true },
  { title: '投资期数', width: 200, sorter: true, dataIndex: 'TZQS', key: 'TZQS', dispaly: true, filter: true, export: true },
  { title: '成功投资期数', width: 200, sorter: true, dataIndex: 'CGTZQS', key: 'CGTZQS', dispaly: true, filter: true, export: true },
  { title: '最近申购日期', width: 120, sorter: true, key: 'ZJSGRQ', caption: "ZJSGRQ", render: data => datetime.format(data.ZJSGRQ, "yyyy-MM-dd"), dispaly: true, filter: true, export: true },
  { title: '最近处理信息', width: 200, sorter: true, dataIndex: 'ZJCLXX', key: 'ZJCLXX', dispaly: true, filter: true, export: true },
  { title: '交易折扣率', width: 120, sorter: true, key: 'JYZKL', dataIndex: "JYZKL", dispaly: true, canEdit: true, export:true },
  { title: '交易机构名称', width: 200, sorter: true, dataIndex: 'JYJGMC', key: 'JYJGMC', dispaly: true, filter: true, export: true },
  { title: '客户经理', width: 120, sorter: true, dataIndex: 'KHJLDM', key: 'KHJLDM', dispaly: true, filter: true, export: true },
  { title: '客户经理名称', width: 160, sorter: true, dataIndex: 'KHJLMC', key: 'KHJLMC', dispaly: true, filter: true, export: true },
  { title: '归属支行', width: 120, sorter: true, dataIndex: 'GSZH', key: 'GSZH', dispaly: true, filter: true, export: true },
  { title: '定投申请日期', width: 120, sorter: true, key: 'DTSQRQ', caption: "DTSQRQ", render: data => datetime.format(data.DTSQRQ, "yyyy-MM-dd"), dispaly: true, filter: true, export: true },
  { title: '结束标志', width: 120, sorter: true, dataIndex: 'JSBZ', key: 'JSBZ', dispaly: true, filter: true, export: true },
];
const controls = [
  { name: 'DTID', required: true, type: 'text', label: '导入年月', grid: 12 / 24, placeholder: "按YYYYMM格式输入,例如:202101", min: 6, max: 6 },
  { name: 'DTBH', type: 'text', label: '定投编号', grid: 12 / 24 },
  { name: 'YHZH', type: 'text', label: '银行账号', grid: 12 / 24 },
  { name: 'KHMC', type: 'text', label: '客户名称', grid: 12 / 24 },
  { name: 'ZJHM', type: 'text', label: '证件号码', grid: 12 / 24 },
  { name: 'TAMC', type: 'text', label: 'TA名称', grid: 12 / 24 },
  { name: 'CPDM', type: 'text', label: '产品代码', grid: 12 / 24 },
  { name: 'CPMC', type: 'text', label: '产品名称', grid: 12 / 24 },
  { name: 'TZJE', required: false, type: 'number', label: '投资金额', grid: 12 / 24, dataType: "number" },
  { name: "TZR", label: "投资日", dataType: "number", type: "number", grid: 12 / 24 },
  { name: 'TZQS', type: 'text', label: '投资期数', grid: 12 / 24 },
  { name: 'CGTZQS', type: 'text', label: '成功投资期数', grid: 12 / 24 },
  { name: "ZJSGRQ", label: "最近申购日期", dataType: "date", type: "date", grid: 12 / 24 },
  { name: 'ZJCLXX', type: 'text', label: '最近处理信息', grid: 12 / 24 },
  { name: 'JYZKL', required: false, type: 'number', label: '交易折扣率', grid: 12 / 24, dataType: "number" },
  { name: 'JYJGMC', type: 'text', label: '交易机构名称', grid: 12 / 24 },
  { name: 'KHJLDM', type: 'text', label: '客户经理', grid: 12 / 24 },
  { name: 'KHJLMC', type: 'text', label: '客户经理名称', grid: 12 / 24 },
  { name: 'GSZH', type: 'text', label: '归属支行', grid: 12 / 24 },
  { name: "DTSQRQ", label: "定投申请日期", dataType: "date", type : "date", grid: 12 / 24 },
  { name: 'JSBZ', type: 'text', label: '结束标志', grid: 12 / 24 },
  { name: 'DRJG', type: 'text', ignore: true, label: '导入结果', grid: 12 / 24 },
]
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class LSJJDTDRTJForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      ny: moment().subtract(1, 'month'),
      searchData: {},
      dataList: []
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID: this.props.permID }
    });
    this.loadData();
  }
  loadData() {
    let ny = this.state.ny.format("YYYYMM")
    let { permID, popedomTypes, userID, orgID, pOrgID } = this.props
    const pTypes = popedomTypes[permID]
    let whereItems = [];
    let WhereCauses = [];
    if (pTypes.indexOf('4') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('3') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "DPID",
        Operator: "=",
        FieldValues: '' + orgID
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('J') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "PDID",
        Operator: "=",
        FieldValues: '' + pOrgID
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('1') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "EMID",
        Operator: "=",
        FieldValues: '' + userID
      })
    }
    WhereCauses.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    let seeks = WhereCauses
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20, seeks }
    });
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  findList() {
    let ny = ""
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      let d = new Date(values.NY)
      ny = datetime.format(d, 'yyyyMM')
    });
    let { permID, popedomTypes, userID, orgID, pOrgID } = this.props
    const pTypes = popedomTypes[permID]
    let whereItems = [];
    let WhereCauses = [];
    if (pTypes.indexOf('4') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('3') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "DPID",
        Operator: "=",
        FieldValues: '' + orgID
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('J') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "PDID",
        Operator: "=",
        FieldValues: '' + pOrgID
      })
    } else if (pTypes.indexOf('4') === -1 && pTypes.indexOf('1') !== -1) {
      whereItems.push({
        FieldName: "DTID",
        Operator: "=",
        FieldValues: ny
      }, {
        FieldName: "EMID",
        Operator: "=",
        FieldValues: '' + userID
      })
    }
    WhereCauses.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    let seeks = WhereCauses
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20, seeks }
    });
  }
  searchHandle(data) {
    this.state.searchData = data
  };
  tzsd() {
    let ny = ""
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      let d = new Date(values.NY)
      ny = datetime.format(d, 'yyyyMM')
    });
    let n = ny.toString().substring(0, 4)
    let y = ny.toString().substring(4, 6)
    Modal.confirm({
      title: '提示',
      content: `你确认锁定【` + n + `年` + y + `月】的客户经理调整吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        otherService.JjTzsd2({ ny }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('锁定成功！')
          } else {
            message.error('锁定失败！' + data)
            return;
          }
        }.bind(this)).catch(function (ex) {
          console.log('请求出错', ex)
        });
      }
    });
  }
  onSelectChangeHandler(newList) {
    this.setState({ dataList: newList })
  }
  jjyjtz() {
    const len = this.props.selectedRowKeys.length;
    if (len === 0) {
      message.error('请选择要调整的数据行！');
      return;
    }
    let isOK = true;
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      if (!err) {
        if (values.YG === undefined || values.YG === '') {
          message.error('客户经理不能为空！');
          isOK = false;
        }
      }
    });
    if (!isOK) {
      return;
    }
    if (this.state.dataList[0].ISSD === 1) {
      message.error('该月的数据调整已结束，不能进行调整了。');
      return
    }
    let key = this.props.selectedRowKeys[0]
    let emid = this.state.searchData.ID
    Modal.confirm({
      title: '提示',
      content: `你确认要调整给客户经理【` + this.state.searchData.Name + `(` + this.state.searchData.No + `)` + `】吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        otherService.Jjyjtz2({ key, emid }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('调整成功！')
            this.componentDidMount()
          } else {
            message.error('调整失败！' + data)
            return;
          }
        }.bind(this)).catch(function (ex) {
          console.log('请求出错', ex)
        });
      }
    });
  }
  tzjs() {
    let ny = ""
    const form = this.refs.EditForm.getForm();
    form.validateFields((err, values) => {
      let d = new Date(values.NY)
      ny = datetime.format(d, 'yyyyMM')
    });
    let n = ny.toString().substring(0, 4)
    let y = ny.toString().substring(4, 6)
    Modal.confirm({
      title: '提示',
      content: `你确认解除【` + n + `年` + y + `月】的客户经理调整锁定吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        otherService.JjTzjs2({ ny }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('锁定成功！')
          } else {
            message.error('锁定失败！' + data)
            return;
          }
        }.bind(this)).catch(function (ex) {
          console.log('请求出错', ex)
        });
      }
    });
  }
  render() {
    let { record, permID, popedomTypes } = this.props
    const pTypes = popedomTypes[permID]
    let controlsFilter = []
    controlsFilter =
      [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month' , layout: { labelSpan: 8, wrapperSpan: 15 }},
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
          ], grid: 2 / 24
        },
      ];
    if (pTypes.indexOf('4') !== -1) {
      controlsFilter = [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month' , layout: { labelSpan: 8, wrapperSpan: 15 }},
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
            { value: '2', label: '锁定', onClick: this.tzsd.bind(this) },
            { value: '3', label: '解锁', onClick: this.tzjs.bind(this) },

          ], grid: 4 / 24
        },
      ];
    }
    if (pTypes.indexOf('2') !== -1) {
      controlsFilter = [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month', layout: { labelSpan: 8, wrapperSpan: 15 } },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
          ], grid: 2 / 24
        },
        { name: 'YG', required: false, type: 'search', label: '客户经理', grid: 5 / 24, layout: { labelSpan: 8, wrapperSpan: 15 }, fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.searchHandle.bind(this), permID: permID } },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '调整', onClick: this.jjyjtz.bind(this) },
          ], grid: 2 / 24
        },
      ];
    }
    if (pTypes.indexOf('2') !== -1 && pTypes.indexOf('4') !== -1) {
      controlsFilter = [
        { name: 'NY', required: true, type: 'month', label: '日期', grid: 4 / 24, dataType: 'month' , layout: { labelSpan: 8, wrapperSpan: 15 }},
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '查询', onClick: this.findList.bind(this) },
          ], grid: 2 / 24
        },
        { name: 'YG', required: false, type: 'search', label: '客户经理', grid: 5 / 24, layout: { labelSpan: 8, wrapperSpan: 15 }, fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.searchHandle.bind(this), permID: permID } },
        {
          name: 'BT', required: false, type: 'button-group',
          data: [
            { value: '1', label: '调整', onClick: this.jjyjtz.bind(this) },
            { value: '2', label: '锁定', onClick: this.tzsd.bind(this) },
            { value: '3', label: '解锁', onClick: this.tzjs.bind(this) },

          ], grid: 4 / 24
        },
      ];
    }
    let ny = this.state.ny.format("YYYYMM")
    const seekRecord = { NY: ny }
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            <EditFrom ref="EditForm" daoName={daoName} controls={controlsFilter} record={seekRecord} clearItemMargin={true} />
          </div>
          <DataTable ref="paraTable" daoName={daoName} columns={columns} controls={controls} permID={permID} onSelectChange={this.onSelectChangeHandler.bind(this)} />
        </div>
      </div>
    )
  }
}
function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes, odsDate } = state.menus;
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record, odsDate,
  }
}
LSJJDTDRTJForm = connect(mapStateToProps)(LSJJDTDRTJForm)
export default LSJJDTDRTJForm;

let render = (props) => React.createElement(LSJJDTDRTJForm, props);
let f = new Factory()
f.set("LSJJDTDRTJForm", render)
